'use client';

import React, { useState } from 'react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Badge from '@/components/ui/Badge';
import { 
  Upload, 
  Download, 
  HardDrive,
  CheckCircle,
  Loader,
  Image,
  FileText,
  Monitor,
  Server
} from 'lucide-react';

export default function ModelImagesPage() {
  const [uploading, setUploading] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  const modelImages = [
    {
      id: '1',
      name: 'PowerGrid-Large-v1.2',
      version: 'v1.2',
      size: '1.2GB',
      status: 'uploaded',
      created_at: '2024-12-01T10:00:00Z',
      description: '电力领域大模型 v1.2版本',
      checksum: 'sha256:a1b2c3d4...',
      load_status: 'loaded'
    },
    {
      id: '2',
      name: 'PowerGrid-Vision-v2.0',
      version: 'v2.0',
      size: '2.8GB',
      status: 'uploading',
      created_at: '2024-12-02T14:30:00Z',
      description: '电力设备视觉识别模型',
      checksum: 'sha256:e5f6g7h8...',
      load_status: 'pending',
      upload_progress: 75
    },
    {
      id: '3',
      name: 'PowerGrid-Sequence-v1.5',
      version: 'v1.5',
      size: '0.8GB',
      status: 'uploaded',
      created_at: '2024-11-28T09:15:00Z',
      description: '电力序列数据分析模型',
      checksum: 'sha256:i9j0k1l2...',
      load_status: 'loading',
      load_progress: 45
    }
  ];

  const targetNodes = [
    {
      id: 'cloud_node_1',
      name: '云端节点1',
      type: 'cloud',
      status: 'online',
      location: '北京数据中心',
      resources: {
        cpu: '32 cores',
        memory: '128GB',
        gpu: '8x V100'
      }
    },
    {
      id: 'edge_node_1',
      name: '边缘节点1',
      type: 'edge',
      status: 'online',
      location: '变电站A',
      resources: {
        cpu: '8 cores',
        memory: '32GB',
        gpu: '1x T4'
      }
    },
    {
      id: 'edge_node_2',
      name: '边缘节点2',
      type: 'edge',
      status: 'online',
      location: '变电站B',
      resources: {
        cpu: '8 cores',
        memory: '32GB',
        gpu: '1x T4'
      }
    }
  ];

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setSelectedFile(file);
    }
  };

  const handleUpload = () => {
    if (!selectedFile) return;
    setUploading(true);
    // 模拟上传过程
    setTimeout(() => {
      setUploading(false);
      setSelectedFile(null);
    }, 3000);
  };

  const getStatusBadge = (status: string, progress?: number) => {
    switch (status) {
      case 'uploaded':
        return <Badge variant="success">已上传</Badge>;
      case 'uploading':
        return <Badge variant="info">上传中 {progress && `(${progress}%)`}</Badge>;
      case 'loaded':
        return <Badge variant="success">已加载</Badge>;
      case 'loading':
        return <Badge variant="info">加载中 {progress && `(${progress}%)`}</Badge>;
      case 'pending':
        return <Badge variant="default">待处理</Badge>;
      case 'failed':
        return <Badge variant="error">失败</Badge>;
      default:
        return <Badge variant="default">{status}</Badge>;
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">模型镜像传输</h1>
          <p className="text-sm text-gray-600 mt-0.5">模型镜像上传、管理与节点部署</p>
        </div>
        <div className="flex gap-3">
          <Button
            onClick={() => document.getElementById('file-upload')?.click()}
            variant="primary"
            size="sm"
          >
            <Upload className="h-4 w-4 mr-2" />
            上传镜像
          </Button>
          <Button variant="secondary" size="sm">
            <Monitor className="h-4 w-4 mr-2" />
            节点管理
          </Button>
        </div>
      </div>

      {/* 上传区域 */}
      <Card className="p-6">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">模型镜像上传</h3>
        <div className="border-2 border-dashed border-gray-300 rounded-lg p-8">
          <div className="text-center">
            <Upload className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                         <h4 className="text-lg font-medium text-gray-900 mb-2">
               {selectedFile?.name || '选择模型镜像文件'}
             </h4>
            <p className="text-gray-600 mb-4">
              支持 .tar, .docker, .onnx 等格式，最大支持 10GB
            </p>
            
            <input
              id="file-upload"
              type="file"
              className="hidden"
              accept=".tar,.docker,.onnx,.pkl,.pth"
              onChange={handleFileSelect}
            />
            
            <div className="flex gap-3 justify-center">
              <Button
                onClick={() => document.getElementById('file-upload').click()}
                variant="secondary"
              >
                选择文件
              </Button>
              {selectedFile && (
                <Button
                  onClick={handleUpload}
                  disabled={uploading}
                  className="bg-blue-600 hover:bg-blue-700 text-white"
                >
                  {uploading ? (
                    <>
                      <Loader className="h-4 w-4 mr-2 animate-spin" />
                      上传中
                    </>
                  ) : (
                    <>
                      <Upload className="h-4 w-4 mr-2" />
                      开始上传
                    </>
                  )}
                </Button>
              )}
            </div>
          </div>
        </div>
        
        {selectedFile && (
          <div className="mt-4 p-4 bg-gray-50 rounded-lg">
            <h5 className="font-medium text-gray-900 mb-2">文件信息</h5>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600">文件名:</span>
                <span className="ml-2 font-medium">{selectedFile.name}</span>
              </div>
              <div>
                <span className="text-gray-600">文件大小:</span>
                <span className="ml-2 font-medium">{(selectedFile.size / 1024 / 1024).toFixed(2)} MB</span>
              </div>
              <div>
                <span className="text-gray-600">文件类型:</span>
                <span className="ml-2 font-medium">{selectedFile.type || '未知'}</span>
              </div>
              <div>
                <span className="text-gray-600">修改时间:</span>
                <span className="ml-2 font-medium">{new Date(selectedFile.lastModified).toLocaleDateString()}</span>
              </div>
            </div>
          </div>
        )}
      </Card>

      {/* 镜像列表 */}
      <Card className="p-6">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">模型镜像列表</h3>
        <div className="space-y-4">
          {modelImages.map((image) => (
            <div key={image.id} className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="flex items-center justify-center w-12 h-12 bg-blue-100 rounded-lg">
                    <Image className="h-6 w-6 text-blue-600" aria-label="Model image icon" />
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-900">{image.name}</h4>
                    <p className="text-sm text-gray-600">{image.description}</p>
                    <div className="flex items-center space-x-4 mt-1 text-xs text-gray-500">
                      <span>版本: {image.version}</span>
                      <span>大小: {image.size}</span>
                      <span>创建: {new Date(image.created_at).toLocaleDateString()}</span>
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center space-x-3">
                  <div className="text-right">
                    <div className="flex items-center space-x-2 mb-1">
                      {getStatusBadge(image.status, image.upload_progress)}
                      {getStatusBadge(image.load_status, image.load_progress)}
                    </div>
                    <div className="text-xs text-gray-500">
                      校验: {image.checksum}
                    </div>
                  </div>
                  
                  <div className="flex flex-col gap-1">
                    <Button size="sm" variant="secondary">
                      <Download className="h-3 w-3 mr-1" />
                      加载
                    </Button>
                    <Button size="sm" variant="secondary">
                      <FileText className="h-3 w-3 mr-1" />
                      详情
                    </Button>
                  </div>
                </div>
              </div>
              
              {/* 进度条 */}
              {(image.upload_progress || image.load_progress) && (
                <div className="mt-3">
                  <div className="flex items-center justify-between text-sm mb-1">
                    <span className="text-gray-600">
                      {image.upload_progress ? '上传进度' : '加载进度'}
                    </span>
                    <span className="font-medium">
                      {image.upload_progress || image.load_progress}%
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                      style={{ width: `${image.upload_progress || image.load_progress}%` }}
                    />
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      </Card>

      {/* 节点管理 */}
      <Card className="p-6">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">目标节点管理</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {targetNodes.map((node) => (
            <div key={node.id} className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center space-x-3">
                  <div className={`flex items-center justify-center w-10 h-10 rounded-lg ${
                    node.type === 'cloud' ? 'bg-blue-100' : 'bg-green-100'
                  }`}>
                    {node.type === 'cloud' ? (
                      <Server className={`h-5 w-5 ${node.type === 'cloud' ? 'text-blue-600' : 'text-green-600'}`} />
                    ) : (
                      <Monitor className={`h-5 w-5 ${node.type === 'cloud' ? 'text-blue-600' : 'text-green-600'}`} />
                    )}
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-900">{node.name}</h4>
                    <p className="text-sm text-gray-600">{node.location}</p>
                  </div>
                </div>
                <Badge variant={node.status === 'online' ? 'success' : 'error'}>
                  {node.status === 'online' ? '在线' : '离线'}
                </Badge>
              </div>
              
              <div className="space-y-1 text-sm text-gray-600">
                <div className="flex justify-between">
                  <span>CPU:</span>
                  <span className="font-medium">{node.resources.cpu}</span>
                </div>
                <div className="flex justify-between">
                  <span>内存:</span>
                  <span className="font-medium">{node.resources.memory}</span>
                </div>
                <div className="flex justify-between">
                  <span>GPU:</span>
                  <span className="font-medium">{node.resources.gpu}</span>
                </div>
              </div>
              
              <div className="mt-4 flex gap-2">
                <Button size="sm" className="flex-1">
                  <Download className="h-3 w-3 mr-1" />
                  部署
                </Button>
                <Button size="sm" variant="secondary">
                  <Monitor className="h-3 w-3 mr-1" />
                  监控
                </Button>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* 传输统计 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-600">总镜像数</h3>
              <p className="text-2xl font-bold text-gray-900 mt-2">12</p>
            </div>
            <HardDrive className="h-8 w-8 text-blue-600" />
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-600">总存储量</h3>
              <p className="text-2xl font-bold text-gray-900 mt-2">45.2GB</p>
            </div>
            <Server className="h-8 w-8 text-green-600" />
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-600">在线节点</h3>
              <p className="text-2xl font-bold text-gray-900 mt-2">8/10</p>
            </div>
            <Monitor className="h-8 w-8 text-yellow-600" />
          </div>
        </Card>
        
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-600">传输成功率</h3>
              <p className="text-2xl font-bold text-gray-900 mt-2">98.5%</p>
            </div>
            <CheckCircle className="h-8 w-8 text-purple-600" />
          </div>
        </Card>
      </div>
    </div>
  );
} 